package com.kedll.library.receiver;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;

import com.kedll.library.util.CollectionUtils;

import java.util.List;
import java.util.Stack;

/**
 * Created by slj on 2014/10/20.
 */
public class ActivitiesManager {
    public Stack<Activity> getActivityStack() {
        return activityStack;
    }

    private Stack<Activity> activityStack = new Stack<Activity>();

    private static ActivitiesManager instance;

    public static ActivitiesManager getInstance() {
        if (instance == null) {
            synchronized (ActivitiesManager.class) {
                if (instance == null) {
                    instance = new ActivitiesManager();
                }
            }
        }
        return instance;
    }


    public void addActivity(Activity activity) {
        activityStack.push(activity);
    }

    public Activity getActivity() {
        if (activityStack.isEmpty())
            return null;
        return activityStack.peek();
    }

    public void removeActivity(Activity activity) {
        activityStack.remove(activity);
    }

    public Activity currentActivity() {
        if (CollectionUtils.isEmpty(activityStack)) {
            return null;
        }
        return activityStack.peek();
    }

    public void clearActivitys() {
        activityStack.clear();
    }

    public boolean isForeground() {
        return currentActivity() != null;
    }

    public boolean isBackground() {
        return currentActivity() == null;
    }

    public int size() {
        return CollectionUtils.size(activityStack);
    }

    public void finish() {
        for (Activity activity : activityStack) {
            activity.finish();
        }
    }

    public void exit() {
        finish();
        System.exit(0);
    }

    /**
     * 判断是否在前台
     *
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
    public static boolean isAppForeground(Context context) {

        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                return appProcess.importance ==
                        ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
            }
        }
        return false;
    }
}
